package com.td.library.media.video;

import com.td.library.ResourceTable;
import com.td.library.config.Constant;
import com.td.library.utils.FileUtils;
import com.td.library.utils.LogUtil;
import com.td.library.utils.TextUtils;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.components.surfaceprovider.SurfaceProvider;
import ohos.agp.graphics.Surface;
import ohos.agp.graphics.SurfaceOps;
import ohos.agp.window.dialog.ToastDialog;
import ohos.media.common.AVDescription;
import ohos.media.common.sessioncore.AVElement;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * MainAbilitySlice
 */
public class VideoAbilitySlice extends AbilitySlice {
    private static final String TAG = VideoAbilitySlice.class.getSimpleName();

    private SurfaceProvider surfaceProvider;

    private Text titleText;

    private VideoPlayerPlugin videoPlayerPlugin;

    private Surface surface;

    private String filePath;
    private String fileName;
    private SurfaceCallBack callback;
    private DirectionalLayout directionalLayout;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_video_ability_slice);
        LogUtil.info(TAG, "onStart ");
        addSurfaceProvider();
        initPlayer();
        initComponents();

        initFileInfo(intent);
    }

    private void addSurfaceProvider() {
        surfaceProvider = new SurfaceProvider(this);

        if (surfaceProvider.getSurfaceOps().isPresent()) {
            callback = new SurfaceCallBack();
            surfaceProvider.getSurfaceOps().get().addCallback(callback);
            surfaceProvider.pinToZTop(true);
            LogUtil.info(TAG, "addSurfaceProvider ");
        }

        directionalLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_directionalLayout);
        directionalLayout.addComponent(surfaceProvider);
    }

    private void initPlayer() {
        videoPlayerPlugin = new VideoPlayerPlugin(getApplicationContext());
    }

    private void initComponents() {
        titleText = (Text) findComponentById(ResourceTable.Id_videoTitle_text);

        Component playButton = findComponentById(ResourceTable.Id_play_button);
        Component pauseButton = findComponentById(ResourceTable.Id_pause_button);
        Component seekButton = findComponentById(ResourceTable.Id_seek_button);
        Component downloadVideoButton = findComponentById(ResourceTable.Id_download_button);

        playButton.setClickedListener((Component component) -> videoPlayerPlugin.startPlay());
        pauseButton.setClickedListener(component -> videoPlayerPlugin.pausePlay());
        seekButton.setClickedListener(component -> videoPlayerPlugin.seek());
        downloadVideoButton.setClickedListener(component -> {
            ThreadPoolManager.getInstance().execute(() -> {
                File videoFile = new File(filePath);
                try (FileInputStream fileInputStream = new FileInputStream(videoFile)) {
                    Date date = new Date(System.currentTimeMillis());
                    String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                    SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                    boolean success = FileUtils.saveToDownloads(getApplicationContext(), fileInputStream, videoFile.getPath(),
                            sdf.format(date) + "————" + videoFile.getName());
                    getUITaskDispatcher().asyncDispatch(() -> {
                        new ToastDialog(getContext())
                                .setText("视频下载是否成功：" + success)
                                .show();
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        });
    }

    private void initFileInfo(Intent intent) {
        filePath = intent.getStringParam(Constant.INTENT_STR_FILE_PATH);
        LogUtil.info(TAG, "filePath " + filePath);
        if (TextUtils.isEmpty(filePath)) {
            LogUtil.error(TAG, "initAVElement filePath isEmpty" );
            return;
        }
        fileName = FileUtils.getFileName(filePath);
        if (TextUtils.isEmpty(fileName)) {
            LogUtil.error(TAG, "initAVElement filePath isEmpty" );
            return;
        }
    }

    private void initAVElement() {
        AVDescription avDescription =
                new AVDescription.Builder().setTitle(fileName).setIMediaUri(Uri.parse(filePath)).setMediaId(filePath).build();
        String itemText = avDescription.getTitle().toString();
        titleText.setText(itemText);
        AVElement avElement = new AVElement(avDescription, AVElement.AVELEMENT_FLAG_PLAYABLE);
        videoPlayerPlugin.startPlay(avElement, surface);
    }

    @Override
    public void onStop() {
        videoPlayerPlugin.release();
        if (surfaceProvider.getSurfaceOps().isPresent()) {
            surfaceProvider.getSurfaceOps().get().removeCallback(callback);
            surfaceProvider.pinToZTop(false);
            LogUtil.info(TAG, "onStop  removeCallback");
        }
        directionalLayout.removeAllComponents();
        surfaceProvider.removeFromWindow();
        surfaceProvider.release();
        super.onStop();
        LogUtil.info(TAG, "onStop");
    }

    /**
     * SurfaceCallBack
     */
    class SurfaceCallBack implements SurfaceOps.Callback {
        @Override
        public void surfaceCreated(SurfaceOps callbackSurfaceOps) {
            if (surfaceProvider.getSurfaceOps().isPresent()) {
                surface = surfaceProvider.getSurfaceOps().get().getSurface();
                LogUtil.info(TAG, "surface set");
                initAVElement();
            }
        }

        @Override
        public void surfaceChanged(SurfaceOps callbackSurfaceOps, int format, int width, int height) {
            LogUtil.info(TAG, "surface changed");
        }

        @Override
        public void surfaceDestroyed(SurfaceOps callbackSurfaceOps) {
            LogUtil.info(TAG, "surface destroyed");
        }
    }
}
